package com.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import androidx.annotation.RequiresApi;
import com.bluetooth.ble.BluetoothLeService;
import com.itianshan.wheel.R;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class BluetoothIOClass extends Activity {
    private String mDeviceName;  //蓝牙设备名称
    public String mDeviceAddress;  //蓝牙设备地址
    public BluetoothLeService mBluetoothLeService; //系统蓝牙服务
    public TextView mConnectionState;
    public boolean mConnected = false;
    public int ErrorMsg; //错误消息
    public boolean connect_status_bit=false;
    private int connect_count = 0;

    public long lastCommandTime=0;  //最后接收到控制信号的时间，超时停止行动
    private final Timer timer = new Timer();
    private TimerTask task;
    private boolean send_hex=true;

    public BluetoothIOClass(String mDeviceAddress, String deviceName , boolean isCloudCar) {
        this.mDeviceName = deviceName;
        this.mDeviceAddress = mDeviceAddress;
        if (mBluetoothLeService != null) {
            final boolean result = mBluetoothLeService.connect(mDeviceAddress);
        } else {
            Log.e("Debug", "deviceAddress:"+mDeviceAddress.toString());
        }
        if(isCloudCar) {
            checkCommandTimeOut();
        }
    }
    public void setCommandTime(long ts){
        this.lastCommandTime = ts;
    }
    //云端控制时，每100毫秒检测最后一次控制信号的时间，超时停车
    private void checkCommandTimeOut(){
        task = new TimerTask() {
            @Override
            public void run() {
                if(lastCommandTime>0 && System.currentTimeMillis()-lastCommandTime>1000){
                    mBluetoothLeService.txxx("{\"dir\":0}\r\n", send_hex);//方向回正
                    mBluetoothLeService.txxx("{\"spe\":0}\r\n", send_hex);//速度0
                }
            }
        };
        timer.schedule(task, 0, 100);
    }
    public void updateConnectionState(final int resourceId) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(mConnectionState !=null){
                    mConnectionState.setText(resourceId);
                }
            }
        });
    }
    public final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            if (!mBluetoothLeService.initialize()) {
            }
            // Automatically connects to the device upon successful start-up initialization.
            mBluetoothLeService.connect(mDeviceAddress);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };
    public static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE1);
        return intentFilter;
    }



    public final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                //mConnected = true;


                connect_status_bit=true;

            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                mConnected = false;

                updateConnectionState(R.string.disconnected);
                connect_status_bit=false;

                if( connect_count==0 )
                {
                    connect_count =1;
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }

            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                // Show all the supported services and characteristics on the user interface.
                displayGattServices(mBluetoothLeService.getSupportedGattServices());
            }
            else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) //接收FFE1串口透传数据通道数据
            {
                //displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
                //byte data1;
                //intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);//  .getByteExtra(BluetoothLeService.EXTRA_DATA, data1);

                //displayData( intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA) );
            }
            else if (BluetoothLeService.ACTION_DATA_AVAILABLE1.equals(action)) //接收FFE2功能配置返回的数据
            {
                //displayData1( intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA1) );
            }
            //Log.d("", msg)
        }
    };
    private void displayGattServices(List<BluetoothGattService> gattServices) {


        if (gattServices == null) return;

        if( gattServices.size()>0&&mBluetoothLeService.get_connected_status( gattServices )==2 )//表示为JDY-06、JDY-08系列蓝牙模块
        {
            connect_count = 0;
            if( connect_status_bit )
            {
                mConnected = true;
                mBluetoothLeService.Delay_ms( 100 );
                mBluetoothLeService.enable_JDY_ble( 0 );
                mBluetoothLeService.Delay_ms( 100 );
                mBluetoothLeService.enable_JDY_ble( 1 );
                mBluetoothLeService.Delay_ms( 100 );

                byte[] WriteBytes = new byte[2];
                WriteBytes[0] = (byte) 0xE7;
                WriteBytes[1] = (byte) 0xf6;
                mBluetoothLeService.function_data( WriteBytes );// 发送读取所有IO状态


                updateConnectionState(R.string.connected);
                //密码
                enable_pass();
            }else{
                ErrorMsg = R.string.not_connected;
                //Toast.makeText(this, "Deleted Successfully!", Toast.LENGTH_LONG).show();
                //Toast toast = Toast.makeText(getBaseContext(), "设备没有连接！", Toast.LENGTH_SHORT);
                //toast.show();
            }
        }
        else if( gattServices.size()>0&&mBluetoothLeService.get_connected_status( gattServices )==1 )//表示为JDY-09、JDY-10系列蓝牙模块
        {
            connect_count = 0;
            if( connect_status_bit )
            {
                mConnected = true;

                mBluetoothLeService.Delay_ms( 100 );
                mBluetoothLeService.enable_JDY_ble( 0 );

                updateConnectionState(R.string.connected);

                //enable_pass();
            }else{
                ErrorMsg = R.string.not_connected;
                //Toast.makeText(this, "Deleted Successfully!", Toast.LENGTH_LONG).show();
                //Toast toast = Toast.makeText(getBaseContext(), "设备没有连接！", Toast.LENGTH_SHORT);
                //toast.show();
            }
        }else
        {
            ErrorMsg = R.string.not_jyd_ble;
            //Toast toast = Toast.makeText(getBaseContext(), "提示！此设备不为JDY系列BLE模块", Toast.LENGTH_SHORT);
            //toast.show();
        }
    }
    String password_value = "123456";
    public void enable_pass()
    {
        mBluetoothLeService.Delay_ms( 100 );
        mBluetoothLeService.set_APP_PASSWORD( password_value );
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1)
            {
                //tvShow.setText(Integer.toString(i++));
                //scanLeDevice(true);
                if (mBluetoothLeService != null) {
                    if( mConnected==false )
                    {
                        updateConnectionState(R.string.connecting);
                        final boolean result = mBluetoothLeService.connect(mDeviceAddress);
                        ErrorMsg = R.string.connect_request_result;
                        //Toast.makeText(getBaseContext(), "Connect request result=" + result,Toast.LENGTH_SHORT).show();
                        //Log.d(TAG, "Connect request result=" + result);
                    }
                }
            }
            if (msg.what == 2)
            {
                try {
                    Thread.currentThread();
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mBluetoothLeService.enable_JDY_ble( 0 );
                try {
                    Thread.currentThread();
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mBluetoothLeService.enable_JDY_ble( 0 );
                try {
                    Thread.currentThread();
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mBluetoothLeService.enable_JDY_ble( 1 );
                try {
                    Thread.currentThread();
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                byte[] WriteBytes = new byte[2];
                WriteBytes[0] = (byte) 0xE7;
                WriteBytes[1] = (byte) 0xf6;
                mBluetoothLeService.function_data( WriteBytes );// 发送读取所有IO状态
            }
            super.handleMessage(msg);
        };
    };

}